package gminet.infra.config;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigProperties {

    private static final String MSG_CONFIG_NOT_INITIALIZED = "Config properties not initialized.";

    private Properties properties;

    private static ConfigProperties configProperties;

	protected ConfigProperties() throws ConfigException {

		super();
	}

    private ConfigProperties(InputStream inputStream) throws ConfigException {

        super();
        initConfig(inputStream);
    }

    public final static void initialize(String fileName) throws ConfigException {

        if (configProperties == null) {
            try {
                FileInputStream configFileIn = new FileInputStream(fileName);
                configProperties = new ConfigProperties(configFileIn);
            } catch (FileNotFoundException fnfe) {
                throw new ConfigException("Arquivo config nao encontrado: " + fileName);
            } catch (Exception e) {
                throw new ConfigException("Erro carregando config: " + fileName);
            }
        }
    }

    public static ConfigProperties getInstance() throws RuntimeException {

        if (configProperties == null) {
            throw new RuntimeException(MSG_CONFIG_NOT_INITIALIZED);
        }
        return configProperties;
    }

    private void initConfig(InputStream inputStream) throws ConfigException {

        try {
            this.properties = new Properties();
            this.properties.load(inputStream);
        } catch (Exception e) {
            throw new ConfigException(e.getMessage());
        }
    }

    public String getValue(String propertyName) {

        return this.properties.getProperty(propertyName);
    }

    public String getValue(String propertyName, String defaultValue) {

        return this.properties.getProperty(propertyName, defaultValue);
    }

    public int getIntValue(String propertyName) {

        return getIntValue(propertyName, 0);
    }

    public int getIntValue(String propertyName, int defaultValue) {

        String strValue = getValue(propertyName, String.valueOf(defaultValue));
        int intValue;
        try {
            intValue = Integer.parseInt(strValue);
        } catch (NumberFormatException nfe) {
            intValue = defaultValue;
        }
        return intValue;
    }

}
